package com.zr.planClass.service.impl;

import com.zr.enumpackage.StatusEnum;
import com.zr.planClass.mapper.PlanClassMapper;
import com.zr.planClass.model.*;
import com.zr.planClass.service.PlanClassService;
import com.zr.qianduan.ResultVOBuilder;
import com.zr.util.AllRecords;
import com.zr.util.ErrorMessageClass;
import com.zr.util.ResultBuilderVo;
import com.zr.util.ResultVo;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

/**
 * Created by Hasee on 2019/12/20.
 */
@Service
public class PlanClassServiceImpl implements PlanClassService {
    @Autowired
    private PlanClassMapper planClassMapper;

    @Override
    @Transactional
    public ResultVo add(@Valid List<PlanClassAddVo> planClassAddVo) {
        //根据前端传过来的编码查询数据库，查看是否存在数据！

        /*int codeCount =  planClassMapper.queryByCodeList();
        if (codeCount>0){
            return ResultBuilderVo.error("编码已经存在！");
        }*/
       /* ResultVo yanzheng = yanzheng(planClassAddVo.getName());
        if (!yanzheng.getSuccess()){
            return yanzheng;
        }*/
        PlanClassVo planClassVo = new PlanClassVo();
        BeanUtils.copyProperties(planClassAddVo,planClassVo);
        Date nowDate = new Date();
        planClassVo.setCreateName("张三");
        planClassVo.setCreateTime(nowDate);
        planClassVo.setUpdateName("张三");
        planClassVo.setUpdateTime(nowDate);
//        planClassMapper.addPlanClass(planClassVo);
        return ResultBuilderVo.success();
    }

    @Override
    public ResultVo queryById(Integer id) {
        PlanClassVo planClassVo = planClassMapper.queryById(id);
        if (!planClassVo.getStatus()){
            planClassVo.setStatusName("禁用");
        }
        if (planClassVo.getStatus()){
            planClassVo.setStatusName("启用");
        }
        if (planClassVo==null){
            return ResultBuilderVo.error("查看对象不存在！");
        }
        return ResultBuilderVo.success(planClassVo);
    }

    @Override
    @Transactional
    public ResultVo update(@Valid PlanClassUpdateVo planClassUpdateVo) {
        //要修改的数据是否存在
        PlanClassVo planClassVo2 = planClassMapper.queryById(planClassUpdateVo.getId());
        if (planClassVo2==null){
            return ResultBuilderVo.error("修改对象不存在！");
        }
        //验证名称是否存在
        List<PlanClassVo> planClassVoList =  planClassMapper.queryByName2(planClassUpdateVo.getName());
        if (!CollectionUtils.isEmpty(planClassVoList)){
//            if (!CollectionUtils.isEmpty(planClassVoList)){
                if (planClassVoList.get(0).getId()!=planClassUpdateVo.getId()){
                    return ResultBuilderVo.error("名称已经存在！");
                }
//            }

        }

        PlanClassVo planClassVo = new PlanClassVo();
        BeanUtils.copyProperties(planClassUpdateVo,planClassVo);
        Date nowDate = new Date();
        planClassVo.setUpdateName("张三");
        planClassVo.setUpdateTime(nowDate);
        int update = planClassMapper.updatePlanClass(planClassVo);
        if (update==0){
            return ResultBuilderVo.error("请刷新后重试！");
        }

        return ResultBuilderVo.success();
    }

    @Override
    @Transactional
    public ResultVo updateStatus(@Valid PlanClassUpdateStatusVo planClassUpdateStatusVo) {
        //修改的数据是否存在
        PlanClassVo planClassVo2 = planClassMapper.queryById(planClassUpdateStatusVo.getId());
        if (planClassVo2==null){
            return ResultBuilderVo.error("修改对象不存在！");
        }

        //数据转换
        //修改数据库
        PlanClassVo planClassVo = new PlanClassVo();
        BeanUtils.copyProperties(planClassUpdateStatusVo,planClassVo);
        Date nowDate = new Date();
        planClassVo.setUpdateName("张三");
        planClassVo.setUpdateTime(nowDate);
        planClassMapper.updatePlanClassStatus(planClassVo);
        return ResultBuilderVo.success();
    }

    @Override
    public ResultVo queryPage(PlanClassSelectVo planClassSelectVo) {
        //1.查询条数
        //2.查询数据
        List<PlanClassVo> planClassVoList = planClassMapper.queryPageData(planClassSelectVo);
        if (!CollectionUtils.isEmpty(planClassVoList)){
            for (PlanClassVo planClassVo:planClassVoList){
                if (planClassVo.getStatus()!=null){
                    if (!planClassVo.getStatus()){
                        planClassVo.setStatusName("禁用");
                    }
                    if (planClassVo.getStatus()){
                        planClassVo.setStatusName("启用");
                    }
                }

            }
        }
        int count = planClassMapper.queryPageCount(planClassSelectVo);
        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(planClassVoList);
        allRecords.setTotalNumber(count);
        allRecords.setPageIndex(planClassSelectVo.getPageIndex());
        allRecords.setPageSize(planClassSelectVo.getPageSize());
        allRecords.resetTotalNumber(count);
        //3.设置响应参数
        return ResultBuilderVo.success(allRecords);
    }

    @Override
    public ResultVo importPlanClass(MultipartFile file) throws Exception {
//        1.给用户提供导入模板
//        2.提示版本问题，询问产品经理支持哪种版本的导入格式，使用2007版本的导入模板，根据版本不同，poi导入技术的读取方式不同
        if (!file.getOriginalFilename().contains("xlsx")){
            return ResultBuilderVo.error("文件必须是2007版本！");
        }

        ResultVo<List<PlanClassAddVo>> resultVo = readFile(file);
        if (!resultVo.getSuccess()){
            return resultVo;
        }
        List<PlanClassAddVo> planClassVoList = resultVo.getData();
        ResultVo validate = validate(planClassVoList);
        if (!validate.getSuccess()){
            return validate;
        }
        //批量入库
 //        7.验证数据是否存在也就是是否合法
        ResultVo add = add(planClassVoList);
        if (!add.getSuccess()){
            return add;
        }
        return ResultBuilderVo.success();
    }
    public ResultVo validate(List<PlanClassAddVo> planClassVoList){
        //        5.验证不为空字段是否为空
//        6.验证字符长度是否符合需求
//      //        9.对于需要转换的数据进行数据转换，比如数据库存的数据为数字格式，用户输入的为汉字，需要把汉字转换为数字存储
        //10.验证状态输入的是否是启用禁用。
//        8.验证数据是否重复


        List<String> codeList = new ArrayList<>();
        for (PlanClassAddVo planClassAddVo:planClassVoList){
            if (StringUtils.isEmpty(planClassAddVo.getCode())){
                return ResultBuilderVo.error("编码不能为空！");
            }else{
                if (planClassAddVo.getCode().length()>30){
                    return ResultBuilderVo.error("编码长度不能大于30个字节！");
                }
            }
            if (StringUtils.isEmpty(planClassAddVo.getName())){
                return ResultBuilderVo.error("名称不能为空！");
            }else{
                if (planClassAddVo.getName().length()>30){
                    return ResultBuilderVo.error("名称长度不能大于30个字节！");
                }
            }
            if (StatusEnum.getValue(planClassAddVo.getStatusName())==null){
                return ResultBuilderVo.error("状态只能填写启用或者禁用！");
            }else {
                Integer status = StatusEnum.getValue(planClassAddVo.getStatusName());
                Boolean booleanStatus = status == 1?true:false;
                planClassAddVo.setStatus(booleanStatus);
            }
            codeList.add(planClassAddVo.getCode());
        }
        Set<String> setCode = new HashSet<>(codeList);
        if (setCode.size()!=codeList.size()){
            return ResultBuilderVo.error("编码重复！");
        }
        return ResultBuilderVo.success();
    }

    public ResultVo readFile(MultipartFile file)throws Exception{
        //        3.模板是否是需要导入的模板，验证模板是否正确
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取单元格中的信息 at0是获取sheet1中的数据。
        XSSFSheet sheet = workbook.getSheetAt(0);
        System.out.println(sheet.getRow(sheet.getFirstRowNum()).getCell(0));
        //验证第一列第一行的表格标头信息是否为 “询价单导入”，如果不是，提示模板错误。
        if (!String.valueOf(sheet.getRow(sheet.getFirstRowNum()).getCell(0)).equals("计划大类导入模板")) {
            return ResultBuilderVo.error("模板错误，请检查模板！");
        }
        List<PlanClassAddVo> planClassVoList = new ArrayList<>();
        //遍历excel表格中的所有数据，从第五行开始读取，没有数据时终止遍历。
        for (int i = sheet.getFirstRowNum() + 4; i <= sheet.getLastRowNum(); i++) {
            //读取每一行的数据
            XSSFRow xssfRow = sheet.getRow(i);
            if(xssfRow!=null) {
                String test1 = String.valueOf(xssfRow.getCell(1)).trim();
                String test2 = String.valueOf(xssfRow.getCell(2)).trim();
                String test3 = String.valueOf(xssfRow.getCell(3)).trim();
                if (!test1.equals("")&&!test1.equals("null")
                        ||!test2.equals("")&&!test2.equals("null")
                        ||!test3.equals("")&&!test3.equals("null")){
                    //把每一行的数据放入到实体类中
                    ResultVo<PlanClassAddVo> inquiryImportVo = build(xssfRow);
                    if (!inquiryImportVo.getSuccess()){
                        return inquiryImportVo;
                    }
                    //把实体类中的数据放入到list集合中
                    planClassVoList.add(inquiryImportVo.getData());
                }

            }
        }
        return ResultBuilderVo.success(planClassVoList);
    }



    public ResultVo build(XSSFRow xssfRow){
        PlanClassAddVo planClassAddVo = new PlanClassAddVo();
        //        4.格式问题，必须保持统一格式，统一为字符串格式导入
        try {
            planClassAddVo.setCode(String.valueOf(xssfRow.getCell(1)));
        }catch (Exception e){
            return ResultBuilderVo.error("请检查编码格式是否为字符串格式");
        }

        planClassAddVo.setName(String.valueOf(xssfRow.getCell(2)));
        planClassAddVo.setStatusName(String.valueOf(xssfRow.getCell(3)));
        planClassAddVo.setRemark(String.valueOf(xssfRow.getCell(4)));
        return ResultBuilderVo.success(planClassAddVo);
    }

    public ResultVo yanzheng(String name){
        //根据前端传过来的名称查询数据库，查看是否存在数据！
        int nameCount =  planClassMapper.queryByName(name);
        if (nameCount>0){
            return ResultBuilderVo.error(ErrorMessageClass.PLANLASSSADD);
        }

        return ResultBuilderVo.success();
    }
}
